﻿#region Copyrights Notice
//©2009 Microsoft Corporation.  All rights reserved.
//This portal design is based on the design and some code from DropThings.com which is also licensed under an MS-PL license.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;

using System.Xml;
using System.Xml.Linq;
using Microsoft.Security.Application;
using Microsoft.InformationSecurity.CISF.Portal.Business.PortalFramework;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.TasksService;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.UserControls;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Common;

namespace Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Widgets
{
    public partial class Tasks : System.Web.UI.UserControl, IWeblet
    {
        private IWebletContainer _WebletContainer;

        protected void Page_Load(object sender, EventArgs e)
        {
            //set the label text to nothing
            lblResults.Text = string.Format("");

            //Only task admin, task manager and trusted task user has task user role in them.
            if (!this.Context.User.IsInRole(Utility.GetConfigurationValue("TaskUser")))
            {
                lblResults.Text = string.Format("Insufficient permissions to view tasks.");
                //hide the grid
                gridMyTasks.Visible = false;
            }
        }

        #region Widget Implementation

        void IWeblet.OnControlInitilize(IWebletContainer webContainer)
        {
            this._WebletContainer = webContainer;
        }

        private XElement m_xmlStorage;
        private XElement State
        {
            get
            {
                if (m_xmlStorage == null)
                {
                    string tmpStr = string.Empty;
                    tmpStr = this._WebletContainer.Restore();
                    if (!tmpStr.Equals(string.Empty))
                        m_xmlStorage = XElement.Parse(tmpStr);
                }
                return m_xmlStorage;
            }
        }
        void IWebletActions.DisplaySettings(bool bDisplay)
        {

            SettingsPanel.Visible = bDisplay;
            if (!bDisplay)
            {
                this.BindGrid();
            }
        }

        void IWebletActions.Minimize()
        {
        }
        void IWebletActions.Maximize()
        {
        }
        void IWebletActions.Close()
        {

        }
        void IWebletActions.MaximizeToFullScreen()
        {
        }

        void IWebletActions.UpdateSettings()
        {
        }

        #region Weblet Settings

        //Widget Settings Variables
        public bool IsActive
        {
            get { return State.Element("isactive") == null ? false : bool.Parse(State.Element("isactive").Value); }
            set
            {
                if (State.Element("isactive") == null)
                    State.Add(new XElement("isactive", value));
                else
                    State.Element("isactive").Value = value.ToString();
            }
        }

        protected void SaveSettings_Click(object sender, EventArgs e)
        {
            this._WebletContainer.DisplaySettings(false);
        }
        private void SaveState()
        {
            if (this.State == null)
                return;

            StringBuilder builder = new StringBuilder();
            XmlTextWriter writer = new XmlTextWriter(new StringWriter(builder));
            this.State.WriteTo(writer);

            var xml = builder.ToString();
            this._WebletContainer.Save(xml);
        }

        #endregion

        #endregion


        #region My Tasks Implementation

        /******************************
        Tasks Implementation here...
        *******************************/

        private void BindGrid()
        {
            gridMyTasks.DataBind();
        }

        protected void gridMyTasks_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (ViewState["GridSortDirection"] != null)
                if ((bool)ViewState["GridSortDirection"] == false)
                    ViewState["GridSortDirection"] = true;
                else
                    ViewState["GridSortDirection"] = false;
            else
                ViewState["GridSortDirection"] = false;
            ViewState["SortExpression"] = e.SortExpression;
            e.Cancel = true;
            this.BindGrid();
        }

        protected void gridMyTasks_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridMyTasks.PageIndex = e.NewPageIndex;
            this.BindGrid();
        }

        protected void tasksSource_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            SearchFilterResult filterResult = new SearchFilterResult();
            filterResult.FieldName = "AssignedTo";
            filterResult.Operator = "=";
            filterResult.Values = new string[] { ((CISF.Security.Principal.CISFIdentity)Page.User.Identity).PersonId.ToString() };

            if (!e.ExecutingSelectCount)
            {
                e.Arguments.MaximumRows = gridMyTasks.PageSize;
                e.Arguments.StartRowIndex = (gridMyTasks.PageIndex * gridMyTasks.PageSize) + 1;
                e.InputParameters.Add("field", filterResult.FieldName);
                e.InputParameters.Add("soperator", filterResult.Operator);
                e.InputParameters.Add("values", filterResult.Values);
                if (ViewState["SortExpression"] == null)
                    e.InputParameters.Add("sortField", "TaskStatus");
                else
                    e.InputParameters.Add("sortField", ViewState["SortExpression"]);
                e.InputParameters.Add("sortDescending", ViewState["GridSortDirection"]);
                e.InputParameters.Add("isTaskUser", !(this.Context.User.IsInRole(Utility.GetConfigurationValue("TrustedTaskUser"))));
                e.InputParameters.Add("personID", ((CISF.Security.Principal.CISFIdentity)Page.User.Identity).PersonId);//Test Value:47506
                e.InputParameters.Add("isActiveTasksOnly", false);
            }
        }

        public void Page_Error(object sender, EventArgs e)
        {
            throw new HttpException(500, "Unhandled Exception.");
        }

        #endregion

    }
}